﻿/**
 * TraceListener.cs
 *  Listening server to process GPS trace signals
 *  (first point of entry for GPS broadcasts)
 *  
 *  11-MAY-2013 byasutake
 */

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Data.SqlClient;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;
using System.Web.Script.Serialization;
using Newtonsoft.Json;


/**
 * Trace object holds fields for all data contained in each incoming GPS trace
 */
public class Reporter
{

    public static HttpListener listener = new HttpListener();

    public Reporter()
    {
        
    }

    public void report()
    {
        listener.Prefixes.Add("http://192.168.1.199:13001/");
        listener.Start();
        //Console.WriteLine("Listening...");
        for (; ; )
        {
            HttpListenerContext ctx = listener.GetContext();
            new Thread(new test(ctx).ProcessRequest).Start();
        }
    }
    
}

class test
{
    private HttpListenerContext context;

    public test(HttpListenerContext context)
    {
        this.context = context;
    }

    public void ProcessRequest()
    {

        SqlCommand myCommand = new SqlCommand("select TOP 4 date_time, latitude, longitude " +
                                                "from history " +
                                                "order by date_time desc");
        SqlDataReader myReader = myCommand.ExecuteReader();

        ////
        //JavaScriptSerializer serializer = new JavaScriptSerializer();
        //JsonConvert.SerializeObject(
        //while (myReader.Read())
        //{
            
        //}

        string msg = context.Request.HttpMethod + " " + context.Request.Url;
        Console.WriteLine(msg);

        String responseData = "hello test";
        byte[] byteArray = Encoding.UTF8.GetBytes(responseData);
        context.Response.ContentType = "text/json";
        context.Response.ContentLength64 = byteArray.Length;

        Stream responseStream = context.Response.OutputStream;
        responseStream.Write(byteArray, 0, byteArray.Length);
        responseStream.Close();

        //System.IO.Stream str;
        //String strmContents;
        //Int32 counter, strLen, strRead;
        //// Create a Stream object.
        //str = context.Request.InputStream;
        //// Find number of bytes in stream.
        //strLen = Convert.ToInt32(str.Length);
        //// Create a byte array.
        //byte[] strArr = new byte[strLen];
        //// Read stream into byte array.
        //strRead = str.Read(strArr, 0, strLen);

        //// Convert byte array to a text string.
        //strmContents = "";
        //for (counter = 0; counter < strLen; counter++)
        //{
        //    strmContents = strmContents + strArr[counter].ToString();
        //}
        //Console.WriteLine(strmContents);

    }
}